<template>
  <div class="work-info">
    <h2>工作信息</h2>
    <el-card>
      <el-descriptions title="工作概况" :column="2" border>
        <el-descriptions-item label="总服务天数">{{ totalDays }}天</el-descriptions-item>
        <el-descriptions-item label="总收益">{{ totalEarnings }}元</el-descriptions-item>
        <el-descriptions-item label="服务次数">{{ serviceCount }}次</el-descriptions-item>
        <el-descriptions-item label="我的评分">
          <el-rate
              v-model="guideRate"
              disabled
              show-score
              score-template="{value}分"
              :max="5"
          />
        </el-descriptions-item>
      </el-descriptions>
    </el-card>

    <el-card style="margin-top: 20px;">
      <template #header>
        <div class="clearfix">
          <span>工作记录</span>
        </div>
      </template>
      <el-table :data="workRecords" style="width: 100%" v-loading="loading">
        <el-table-column prop="visitorName" label="游客姓名" width="100"></el-table-column>
        <el-table-column prop="visitorPhone" label="电话" width="120"></el-table-column>
        <el-table-column prop="visitorGender" label="性别" width="80">
          <template #default="scope">
            <span>{{ scope.row.visitorGender === 'M' ? '男' : '女' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="startTime" label="开始时间" width="120">
          <template #default="scope">
            <span>{{ formatDate(scope.row.startTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="endTime" label="结束时间" width="120">
          <template #default="scope">
            <span>{{ formatDate(scope.row.endTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="guideSalary" label="地陪工资(元)" width="100"></el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row)">
              {{ getStatusText(scope.row) }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import workApi from '@/api/guide/work_api.js'
import gRateApi from '@/api/guide/g_rate_api.js'
import { getJwtPayload } from "@/util/auth.js"
import { ElMessage } from 'element-plus'

const workRecords = ref([])
const loading = ref(false)
const guideRate = ref(0) // 评分数据

// 计算总服务天数
const totalDays = computed(() => {
  return workRecords.value.reduce((total, record) => {
    return total + (record.days || 0)
  }, 0)
})

// 计算总收益
const totalEarnings = computed(() => {
  return workRecords.value.reduce((total, record) => {
    return total + (record.guideSalary || 0)
  }, 0)
})

// 计算服务人次
const serviceCount = computed(() => {
  return workRecords.value.length
})

onMounted(async () => {
  await loadWorkRecords()
  await loadGuideRate() // 加载评分
})

// 加载工作记录
const loadWorkRecords = async () => {
  loading.value = true
  try {
    const res = await workApi.getWorkRecords()
    console.log("前端加载工作记录:"+res)
    workRecords.value = res || []
  } catch (error) {
    console.error('加载工作记录失败:', error)
  } finally {
    loading.value = false
  }
}

// 加载地陪评分
const loadGuideRate = async () => {
  try {
    // 从JWT token中获取当前用户ID
    const payload = getJwtPayload();
    if (!payload || (payload.ID == null && payload.id == null)) {
      ElMessage.error('未从 token 中读取到用户 ID');
      return;
    }

    const guideId = Number(payload.ID ?? payload.id);
    if (guideId) {
      const res = await gRateApi.getRate({ guideId });
      // 确保正确处理响应数据
      if (res !== undefined && res !== null) {
        guideRate.value = parseFloat(res.toFixed(1));
      } else {
        guideRate.value = 0;
      }
    }
  } catch (error) {
    console.error('加载评分失败:', error);
    ElMessage.error('加载评分失败: ' + (error.message || '未知错误'));
  }
}


// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  const d = new Date(date)
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
}

// 获取状态文本
const getStatusText = (row) => {
  const now = new Date()
  const start = new Date(row.startTime)
  const end = new Date(row.endTime)

  if (now < start) {
    return '未开始'
  } else if (now >= start && now <= end) {
    return '进行中'
  } else {
    return '已结束'
  }
}

// 获取状态标签类型
const getStatusType = (row) => {
  const now = new Date()
  const start = new Date(row.startTime)
  const end = new Date(row.endTime)

  if (now < start) {
    return 'info'
  } else if (now >= start && now <= end) {
    return 'warning'
  } else {
    return 'success'
  }
}
</script>

<style scoped>
.work-info {
  padding: 20px;
}
</style>
